package com.juvepoland.jpdroid.managers.impl;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.juvepoland.jpdroid.common.JPdroidSecurity;
import com.juvepoland.jpdroid.common.JSONParser;
import com.juvepoland.jpdroid.models.Rank;
import com.juvepoland.jpdroid.models.User;

public class UserManager {
	
	static final String URL_GET_USER = "http://jpdroid.juvepoland.com/get_user_details.php";
	
	JSONParser jParser = new JSONParser();
	
	public User getUser(String username, String password) throws Exception{
		List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("user_password", password ));
        Log.d("parametry: ", username.replace(" ", "%20")+" "+password);
        JSONObject jsonObject = jParser.makeHttpRequest(URL_GET_USER, "GET", params);
        Log.d("jsonObject", jsonObject.toString());
        int success = jsonObject.getInt("success");
        if (success == 1) {
        	JSONArray productObj = jsonObject.getJSONArray("user"); // JSON Array
        	JSONObject userJson = productObj.getJSONObject(0);
        	User user = new User();
        	user.setActive(userJson.getInt(User.D_ACTIVE)==1? true : false);
        	if(user.isActive()){
        		user.setId(userJson.getInt(User.D_ID));
            	user.setUsername(userJson.getString(User.D_USERNAME));
              	user.setAvatarSource(userJson.getString(User.D_AVATAR_SOURCE)); 
            	user.setRank(Rank.getRank(userJson.getInt(User.D_RANK)));
            	return user;
        	}
        	else{
        		throw new Exception("Użytkownik nieaktywny!");
          	}      	
        }
        else{
        	throw new Exception("Błąd: "+jsonObject.getString("message"));
        }
	}
	

}
